//
//  UserControl.swift
//  JoTravel
//
//  Created by otisaldridge on 15/10/12.
//  Copyright © 2015年 zhuxietong. All rights reserved.
//

import UIKit
extension EeAuthControl
{
    public static var LoginControllerClass:UIViewController.Type =  UIViewController.self
}

extension UINavigationController{
   
    private struct __NavAssociatedKeys {
           static var login_block_key = "__login_block_key"
       }
    public var login_block: EeLogin_Finish_Block? {
        get {
//            print("\(self)+IIIIIIIs((+++IIIIIi\(objc_getAssociatedObject(self, &__NavAssociatedKeys.login_block_key))")
            if let obj = objc_getAssociatedObject(self, &__NavAssociatedKeys.login_block_key) as? EeLogin_Finish_Block
            {
                return obj
            }
            return nil
        }
        set {
            objc_setAssociatedObject(self, &__NavAssociatedKeys.login_block_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
//            print("\(self)++s((+++IIIIIi\(objc_getAssociatedObject(self, &__NavAssociatedKeys.login_block_key))")
        }
    }
}

open class EeAuthControl: NSObject {
    public class func getUser(_ need_im:Bool=false,finish_block:@escaping EeLogin_Finish_Block)
    {
        if let user = JoUser.loginUser()
        {
            if need_im
            {
                EeAuthControl.AskImLogin(finish_block)
            }
            else
            {
                finish_block(true,"登录成功".loc,user)
            }
        }
        else
        {
            EeAuthControl.goLoginView(finish_block)
        }
    }
    
    public class func getNewUser(_ finish_block:@escaping EeLogin_Finish_Block)
    {
        if let user = JoUser.loginUser()
        {
            finish_block(true,"登录成功".loc,user)
        }
        else
        {
            let login = EeAuthControl.LoginControllerClass.init()
            if let ctr = login as? CoInputController{
                ctr.fastRigister = true
            }
//            let nav = EeLoginNavController(rootViewController: login)
            let nav = RootNavigationController(rootViewController: login)
            nav.login_block = {(succeed:Bool,msg:String,user:JoUser?) ->()
                in
                finish_block(succeed,msg,user)
            }
            
            if let root = UIApplication.shared.keyWindow?.rootViewController
            {
                root.present(nav, animated: true, completion: { () -> Void in
                })
            }
        }
    }
    
}

extension EeAuthControl
{
    @discardableResult
    class func AskImLogin(_ finish_block:@escaping EeLogin_Finish_Block) ->Bool
    {
        if let can_chat = UserDefaults.standard.object(forKey: "__IM__") as? String
        {
            if can_chat == "NO"
            {
                JoAlertView(info: "提示".loc,"该功能数据连接失败（IM连接失败），请尝试重新登录".loc,"取消".loc).append(title: "重新登录".loc, action: {
                    EeAuthControl.goLoginView(finish_block)
                }).show(at: __controller)
                //                let alert = UIAlertController(title: "该功能数据连接存在问题，请尝试重新登录", canle: "取消", style: UIAlertControllerStyle.actionSheet, actions:
                //                    Action(name: "重新登录", hander: { (alert:UIAlertAction) -> Void in
                //                        UserControl.goLoginView(finish_block)
                //                    })
                //                )
                //
                //                JoTabBarController.rootTabCotroller?.present(alert, animated: true, completion: nil)
                return false
            }
            else
            {
                EeAuthControl.getUser(finish_block: finish_block)
                return true
            }
        }
        return false
    }
    
    class func goLoginView(_ finish_block:@escaping EeLogin_Finish_Block)
    {
        //        let loginBoard = UIStoryboard(name: "Login", bundle: nil)
        //        let login = loginBoard.instantiateViewControllerWithIdentifier("LoginController")
        
        let login = EeAuthControl.LoginControllerClass.init()
//        let nav = EeLoginNavController(rootViewController: login)
        let nav = RootNavigationController(rootViewController: login)
        nav.modalPresentationStyle = .fullScreen

        nav.login_block = {(succeed:Bool,msg:String,user:JoUser?) ->()
            in
            finish_block(succeed,msg,user)
        }
        

        if let root = UIApplication.shared.keyWindow?.rootViewController
        {

            if let _ = root.presentedViewController
            {
                __controller.present(nav, animated: true, completion: nil)
                
            }
            else{
                root.present(nav, animated: true, completion: { () -> Void in
                })
            }
            
        }
        else{
            __controller.present(nav, animated: true, completion: nil)
        }
        
    }
    
    class func IM_Valied() ->Bool
    {
        if let info = UserDefaults.standard.object(forKey: "__IM__") as? String
        {
            if info == "YES" {
                return true
            }
            else
            {
                return false
            }
        }
        
        return false
    }
    
    
    
    class func loginImAcount(_ finish:(Bool,String)->Void)
    {
        
        if JoUser.loginUser() != nil
        {
            /*
             SPKitExample.sharedInstance().loginWithToken(user.token,preloginedBlock: { () -> Void in
             
             finish(true,"im login ok (001)")
             
             }, successBlock: { () -> Void in
             finish(true,"im login ok (002)")
             
             }, failedBlock: { (err:NSError!) -> Void in
             finish(false,"im login failed (000)")
             })
             */
        }
        
    }
}


////
////  UserControl.swift
////  JoTravel
////
////  Created by otisaldridge on 15/10/12.
////  Copyright © 2015年 zhuxietong. All rights reserved.
////
//
//import UIKit
//
//class UserControl: NSObject {
//
//
//    func getUser(finish_block:JoLogin_Finish_Block)
//    {
//        if let user = JoUser.loginUser()
//        {
//            finish_block(succeed: true,msg: "登录成功",user: user)
//        }
//        else
//        {
//
//
//            let loginBoard = UIStoryboard(name: "Login", bundle: nil)
//            let login = loginBoard.instantiateViewControllerWithIdentifier("LoginController")
//
//            let nav = LoginNavController(rootViewController: login)
//
//            nav.login_block = {(succeed:Bool,msg:String,user:JoUser?) ->()
//                in
//                finish_block(succeed: succeed,msg: msg,user: user)
//            }
//
//
//            SideMenuViewController.rootController().presentViewController(nav, animated: true, completion: { () -> Void in
//
//            })
//
////                - (UIViewController *)appRootViewController
////                    {
////                        UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
////                        UIViewController *topVC = appRootVC;
////                        while (topVC.presentedViewController) {
////                            topVC = topVC.presentedViewController;
////                        }
////                        return topVC;
////            }
//
//        }
//
//
//    }
//}


